﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Threading;
using System.Windows.Interop;

using System.Collections;//ArrayList
using Microsoft.Win32;

using System.Collections.ObjectModel;//绑定

namespace EasyX264_ver1._0
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 变量定义区
        /// </summary>
        private Thread EnCodThread;             //转码线程
        private EnCod EnCodobj;                 //转码实例
        private MainParam MainParam;            //存储初始化参数


        private RunParam TEMP;
        private int T = 0;


        /*
        private string PresentParam;            //当前传递的参数
        private string PreaentEnCoder;          //当前传递的编码器
        */

        private bool IsThreadStart = false;     //标记是否已经启动转码线程
        private const int WM_COPYDATA = 0x004A; //进程间传输数据

        [StructLayout(LayoutKind.Sequential)]   //传递数据结构
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;//字符串长度
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;//字符串
        }


        //SupplierCountStruct类中包含上面红色标出的字段名
        private ObservableCollection<RunParam> InfoView = new ObservableCollection<RunParam>();


        /// <summary>
        /// 实现区
        /// </summary>
        public MainWindow()
        {
            //启动界面
            Window start;
            start = new Start();
            start.Show();

            if (!InitProcess()) //调入参数,出错时不启动系统
            {
                //关闭启动界面线程
                start.Close();
                Application.Current.Shutdown();
            }

            DoEvents();
            System.Threading.Thread.Sleep(800);//延时800毫秒

            start.Close();

            InitializeComponent();

            //显示在屏幕中心
            WindowStartupLocation = WindowStartupLocation.CenterScreen;

        }


        //启动界面时不至于假死
        private void DoEvents()
        {
            DispatcherFrame frame = new DispatcherFrame();
            Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
                new DispatcherOperationCallback(delegate(object f)
                {
                    ((DispatcherFrame)f).Continue = false;

                    return null;
                }
                    ), frame);
            Dispatcher.PushFrame(frame);
        }

        //窗口拖拽
        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        //启动按钮
        private void btn_start_Click(object sender, RoutedEventArgs e)
        {
            T++;
            TEMP.Update(T.ToString());
            ListViewItem te = new ListViewItem();
         //   var temp1;

            
            //InfoView.Add(TEMP);
            //InfoView.Insert(0,TEMP);
             // InfoView
           this.info_view.ItemsSource = InfoView;
        //   this.info_view.Items.MoveCurrentTo(InfoView);
        //   info_view.item
           // this.info_view.Items.Add(InfoView);

          //  InfoView.Remove( "hhhhhhhhhhhh");

            /*
            
            if (IsThreadStart == false)//未启动时开始转码
            {          
                (PresentationSource.FromVisual(this) as HwndSource).AddHook(new HwndSourceHook(this.WndProc));//钩子

                //传递执行文件地址(exe地址),参数.
                //arg为参数
                string[] arg = new string[1];
                arg[0] = "--crf 25 --preset veryfast --tune animation -o G:\\temp_video.mp4 G:\\1.m2ts".Trim();
                EnCodobj = new EnCod();
                EnCodobj.filename = @"EnCoder\\x264 ";
                EnCodobj.args = arg;
                EnCodThread = new Thread(new ThreadStart(EnCodobj.init));
                EnCodThread.Start();

                IsThreadStart = true;//标记转码线程已启动
                this.btn_cancel.Visibility = Visibility;//设置取消按钮可见    
            }
             */
        }

        //参数配置按钮
        private void Eidt_Click(object sender, RoutedEventArgs e)
        {
            TEMP = new RunParam("xxxxxxxxx");
            InfoView.Insert(0, TEMP);
        }

        //取消按钮
        private void btn_cancel_Click(object sender, RoutedEventArgs e)
        {
            IsThreadStart = false;

            //提示正在转码,是否取消! 
            if (MessageBox.Show("正在转码,是否取消？\n(取消后不可继续！)", "标题", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            {
                EnCodobj.KILL();//关闭转码进程
                System.Threading.Thread.Sleep(300);

                //删除转码临时文件            
                this.btn_cancel.Visibility = Visibility.Hidden;
                this.output_info.Text = "已取消";
            }
            else
            {
                IsThreadStart = true;
            }
        }

        //启动窗口预处理
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        //关闭按钮
        protected void btn_close_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();

        }

        //文件选择按钮
        private void FileInput_Click(object sender, RoutedEventArgs e)
        {
            //一些临时变量
            String temp_name, temp_path = "";
            int len, t, i;

            OpenFileDialog SelectFile = new OpenFileDialog();
            SelectFile.Title = "选择";
            SelectFile.Multiselect = true;//支持多选
            SelectFile.Filter = "媒体文件|*.mp4;*.mkv;*.mov;*.wmv;*.avi;*.m2ts|MP4|*.mp4|MKV|*.mkv|MOV|*.mov|WMV|*.wmv|AVI|*.avi|M2TS|*.m2ts";//格式

            if (SelectFile.ShowDialog() == true) //点击确定过后
            {
                temp_name = SelectFile.FileName;
                len = temp_name.Length;         //测量完整路径长度

                //逆序检测"/"
                for (i = len - 1; i > 0; i--)
                {
                    if (temp_name[i] == '\\')
                    {
                        break;
                    }
                }
                //提取文件路径，保存在temp_path中
                for (t = 0; t <= i; t++)
                {
                    temp_path += temp_name[t];
                }

                //      ArrayList fileList = new ArrayList();

                foreach (string file in SelectFile.FileNames)
                {
                    FileInfo file_name = new FileInfo(file.Substring(file.LastIndexOf("\\") + 1));

                    listBoxSelectedFile.Items.Add(temp_path + file_name);

                    //fileList.Add(Path);
                    //GetDirectoryName(OpenFileDialog.FileName)              
                    //listBoxSelectedFile.Items.Insert(0,new ListItem(info));
                    //  info_view.Items.Add(new);// temp;

                }
            }
        }


        //重载关闭按钮
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (IsThreadStart == false)
            {
                //未启动转码，直接关闭
                Application.Current.Shutdown();
            }
            else if (EnCodThread.IsAlive)
            {
                if (MessageBox.Show("正在转码，是否关闭程序？\n(关闭后不可继续！)", "标题", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                {
                    EnCodobj.KILL();//关闭转码进程
                    System.Threading.Thread.Sleep(500);
                    //删除转码临时文件
                    //在关闭程序前，将配置文件中"当前所使用参数(NowPara)"修改为"默认参数(DefPara)"

                    Application.Current.Shutdown();
                }
                else
                {
                    e.Cancel = true;
                }
            }
            else
            {
                //未转码时直接关闭
                Application.Current.Shutdown();
            }
        }

        // 窗口过程回调函数
        IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WM_COPYDATA)
            {
                COPYDATASTRUCT cds = (COPYDATASTRUCT)System.Runtime.InteropServices.Marshal.PtrToStructure(lParam, typeof(COPYDATASTRUCT));

                if (cds.lpData == "Error")//出错时设置取消按钮不可见
                {
                    IsThreadStart = false;
                    this.btn_cancel.Visibility = Visibility.Hidden;
                    this.output_info.Text = "Error";
                }

                if (cds.lpData == "Finish")//出错时设置取消按钮不可见
                {
                    if (IsThreadStart == true)
                    {
                        IsThreadStart = false;
                        this.btn_cancel.Visibility = Visibility.Hidden;
                        this.output_info.Text = "Finish";
                    }
                }
                else
                {
                    /////////////////////////////////////////////////////////////////////////////////////////////
                    InfoView.Add(new RunParam(cds.lpData));
                    this.info_view.ItemsSource = InfoView;
                    /////////////////////////////////////////////////////////////////////////////////////////////

                    this.output_info.Text = cds.lpData; //显示获取信息
                }

                //判断编码阶段、结束等(关闭转码线程等操作)...
            }
            return hwnd;
        }

        private void listBoxSelectedFile_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void ListView_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {

        }

        //启动时初始化、自检..
        private bool InitProcess()
        {

            /////////////////////////////////////以下系统文件自检过程////////////////////////////////////////

            if (!File.Exists("themes//Main.EasyX264"))
            {
                MessageBox.Show("系统文件丢失或损坏！\n请重新安装程序");
                return false;
            }

            StreamReader re;
            re = File.OpenText("themes//Main.EasyX264");

            MainParam.ParaNum = int.Parse(re.ReadLine());
            MainParam.NowPara = int.Parse(re.ReadLine());
            MainParam.DefPara = int.Parse(re.ReadLine());

            re.Close();

            /////////////////////////////////////以上系统文件自检过程///////////////////////////////////////

            return true;
        }

    }

    /// <summary>
    /// 主配置结构体
    /// </summary>
    public struct MainParam
    {
        public int ParaNum;    //参数总条数
        public int NowPara;    //当前所使用参数
        public int DefPara;    //默认参数
    }
}
